package cn.riverluoo.effectiveness;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class DtdValidataXml {
	private boolean validate = true;

	public DtdValidataXml(){

	}

	public boolean XMLValidateDTD(File file) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(true);
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			MyHandler mh = new MyHandler();
			builder.setErrorHandler(mh);
			builder.parse(file);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return validate;
	}

	class MyHandler extends DefaultHandler {
		String errorMessage = null;

		public void error(SAXParseException e) throws SAXException {
			errorMessage = e.getMessage();
			System.out.println("一般错误！！！" + errorMessage);
			validate = false;
		}

		public void fatalError(SAXParseException e) throws SAXException {
			errorMessage = e.getMessage();
			System.out.println("严重错误！！！" + errorMessage);
			validate = false;
		}

	}

}
